/**
 * 
 */
package pt.inescid.components.appadaptationlayer.applications.povray;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author Sergio Esteves
 *
 */
public class HandleINI {
	
	//private final static String LOW_RES = "+W80 +H60";
	private final static String MED_RES = "+W320 +H200";
	//private final static String HIGH_RES = "W640 +H480";
	//private final static String REALLY_HIGH_RES = "+W800 +H600";
	private final static String START_ROW_STR = "Start_Row";
	private final static String END_ROW_STR = "End_Row";
	private final static String ANTIALIAS_STR = "Antialias";
	private final static String ANTIALIAS_THRESHOLD_STR = "Antialias_Threshold";
	private final static String OUTPUT_STR = "+O";
	
	public static int generateFile(String location, String resolution, int startRow, int endRow,
			String outputLocation) {		
		try {
			FileWriter fstream = new FileWriter(location);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write("; Automatic generated file - GridP2P");
			out.newLine();
			out.write(resolution);
			out.newLine();
			out.write(START_ROW_STR + "=" + startRow);
			out.newLine();
			out.write(END_ROW_STR + "=" + endRow);
			out.newLine();
			out.write(OUTPUT_STR + outputLocation);
			out.newLine();
			out.close();
		} catch (IOException e) {
			System.err.println("Error: " + e.getMessage());
			return -1;
		}
		return 0;
	}

	public static byte[] generate(String resolution, int startRow, int endRow) {
		String str = "; Automatic generated file - GridP2P\n" + resolution + '\n' +
		START_ROW_STR + "=" + startRow + '\n' + END_ROW_STR + "=" + endRow + '\n' +
		ANTIALIAS_STR + "=On\n" + ANTIALIAS_THRESHOLD_STR + "=0.3\n";
		return str.getBytes();
	}
	
	public static String getResolution(String location) {		
		try {
			FileReader fstream = new FileReader(location);
			BufferedReader in = new BufferedReader(fstream);
			String str = null;
			while((str = in.readLine()) != null)
				if(str.startsWith("+W")) {
					in.close();
					return str;				
				}
			in.close();
		} catch (FileNotFoundException e) {
			System.err.println("FileNotFoundException occurred: " + e.getMessage());
		} catch (IOException e) {
			System.err.println("IOException occurred: " + e.getMessage());
		}
		// resolution by default
		return MED_RES;
	}
	
	public static void main(String[] args) {
		String res = getResolution("POVRAY.ini");
		System.out.println(generate(res,1,3));
	}	
}
